#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* C和指针第6章，课后第一题 */
static const char * find_char(char const *source, const char *chars)
{
	const char *p = NULL;
	if (NULL != source && NULL != chars) {
		for (; *chars != '\0'; chars++) {
			for (p = source; *p != '\0'; p++) {
				if (*p == *chars) 
					return p;
			}
		}

	}
#if 0
	while (*chars != '\0') {
		p = source;
		while (*p != '\0') {
			if (*p == *chars)
				return p;
			p++;
		}
		chars++;
	}
#endif

	return NULL;
}

static char * match_str(char *str, const char *want)
{
	while (*want != '\0') {
		if (*want++ != *str++)
			return NULL;
	}

	return str;
}

/* C和指针第6章，课后第二题 */
static int del_substr(char *str, char const *substr) 
{
	char *p = NULL;	

	while (*str != '\0') {
		p = match_str(str, substr);/* 直到匹配成功才返回有效 */
		if (NULL != p)
			break;
		str++;
	}

	if (NULL != p) {
		while (*str != '\0') {
			*str++ = *p++;/* 从匹配的第一个字符开始直到指向字符'\0' */
		}
		return 1;
	}
	return 0;	
}


/* C和指针第6章，课后第3题 */
static void reverse_string(char *string)
{
	char *start = string;
	char *end = string;
	char ch;

	while (*end != '\0') {
		end++;
	}

	while (end > start) {/* 只有end大于start才需要交换，小于等于的时候就不需要了 */
		//printf("start = %p end = %p\n", start, end);
		ch = *start;
		*start++ = *--end;
		*end = ch;
	}

	return ;
}

int main(void)
{
	int ret = 0;
	char str[100] = "hellowordl";
	reverse_string(str);
	printf("%s\n", str);
	
#if 0
	const char *p = NULL;	
	const char *source  = "ABCDEF";
	//const char *substr = "XRGGGGGSGGSA";
	const char *substr = "ZYX";

	p = find_char("ABCDEF", "XRGGGGGSGGSA");
	//p = strpbrk(source, substr);
	if (p) {
		printf("find the str is %s\n", p);
	} else {
		printf("Not foud substr\n");
	}
	ret = del_substr(str, "ld");

	if (ret) {
		printf("deleted subtr now source str: %s\n", str);
	} else {
		printf("Not deleted subtr now source str: %s\n", str);
	}

#endif

	return 0;
}

